package prj.carmap.mobile.process;

import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 版本更新任务
 *
 */
public class UpdateVersionTask extends AsyncHttpResponseHandler {

	static final String TAG = "UpdateVersionTask";

	//private final static String VERSION_NUM = "versionNum";
	//private final static String VERSION_PATH = "versionLink";

	private static AsyncHttpClient client = new AsyncHttpClient();

	private Context context;

	/**
	 * @param context
	 */
	public UpdateVersionTask(Context context) {
		super();
		this.context = context;
	}

	public void checkVersion() {
		client.get(CarmapApplication.SERVER_URL + "/rest/versionCheck", this);
	}

	public void onSuccess(String content) {
		try
		{
			JSONObject json = new JSONObject(content);
			if (json.has("versionNumber"))
			{
				int version = json.getInt("versionNumber");
				final String path = json.getString("versionLink");
				Log.d(TAG, "versionCheck: versionNumber=" + version + ", versionLink=" + version);

				if (version <= getVersionCode(UpdateVersionTask.this.context)) {
					return;
				}

				new AlertDialog.Builder(context)
						.setTitle(R.string.app_name)
						.setMessage(R.string.version_new)
						.setPositiveButton(R.string.submit,
								new OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Log.d(TAG, "开始更新新版本 " + path);
										Intent service = new Intent(context, DownLoadService.class);
										service.putExtra("url", path);
										context.startService(service);
									}
								})
						.setNegativeButton(R.string.cancel, null)
						.create()
						.show();
			}
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	private int getVersionCode(Context context) {
		PackageManager manager = context.getPackageManager();
		try
		{
			PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
			return info.versionCode;
		}
		catch (NameNotFoundException e)
		{
			e.printStackTrace();
			return -1;
		}
	}

}
